import { getHeroListAPI } from "../../api/hero"
import Variable from "../../constants/index"
import { Hero } from "../../types/hero"

// pages/search/search.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    searchwordlist:[] as string[],
    searchval:'',
    herolist:[] as Hero[]
  },

  async search(){
      wx.showLoading({title:"加载中"})
      if (this.data.searchval) {
        this.setData({
            herolist: await getHeroListAPI({q:this.data.searchval}),
            searchwordlist:[...new Set([this.data.searchval,...this.data.searchwordlist])]
        },()=>{
            wx.setStorageSync(Variable.SEARCH_LIST,JSON.stringify(this.data.searchwordlist))
        })
      }else{
        this.setData({
            herolist: []
          })
      }
      wx.hideLoading()
  },
  toDetail(e:WechatMiniprogram.TouchEvent){
        console.log(e.mark?.heroId);
        wx.navigateTo({
            url: `/pages/hero_detail/hero_detail?heroId=${e.mark?.heroId}`
        })
    },
    toSearch(event:WechatMiniprogram.TouchEvent){
        this.setData({
            searchval:event.mark?.word
        })
        this.search()
    },
    delone(event:WechatMiniprogram.TouchEvent){
        this.setData({
            searchwordlist:this.data.searchwordlist.filter(item=>item!==event.mark?.word)
        },()=>{
            wx.setStorageSync(Variable.SEARCH_LIST,JSON.stringify(this.data.searchwordlist))
        })
    },
    delall(){
        this.setData({
            searchwordlist:[]
        },()=>{
            wx.removeStorageSync(Variable.SEARCH_LIST)
        })
    },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getHistoryList()
  },
  getHistoryList(){
      this.setData({
        searchwordlist : JSON.parse(wx.getStorageSync(Variable.SEARCH_LIST) || "[]") as string[]
      })
      
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})